/**
 * 文件管理弹框
 * @Author: zhangshubin
 * @Date: 2023-12-20 09:14:58
 * @Last Modified by: zhangshubin
 * @Last Modified time: 2023-12-22 17:53:01
 *
 */
import {
  Button,
  Col,
  Form,
  Input,
  Row,
  Select,
  Table,
  TreeSelect,
  Upload,
  UploadFile,
  UploadProps
} from 'antd'
import DraggableDialog from '../DraggableDialog'
import { useEffect, useRef, useState } from 'react'

import './index.less'
import EditorExecutor from '@/executor/EditorExecutor'
import { getStationListByUser, stationAndDeviceList } from '@/api/base'
import { handleTree } from '@/util/TreeUtil'
import { FILE_STATUS, FILE_STATUS_OPTIONS, FILE_TYPE, FILE_TYPE_OPTIONS } from '@/constants'
import * as FileApi from '@/api/file'

interface IProjectDialog {
  title?: string
  fileId?: number
  type: 'add' | 'saveas' | 'edit'
  onClose?: () => void
  onOk?: (file: HFileMeta) => void
}

type FieldType = {
  stationId?: string
  deviceCode?: string
  name?: string
  type: number
  status: number
  desc: string
}

const layout = {
  labelCol: { span: 4 },
  wrapperCol: { span: 20 }
}
const initFormValues = {
  stationId: '',
  deviceCode: '',
  fileName: '',
  type: FILE_TYPE.INDEX,
  status: FILE_STATUS.DRAFT,
  desc: ''
}
export default function ProjectDialog(props: IProjectDialog) {
  const [form] = Form.useForm()
  // 电站数据
  const stationList = useRef([])
  // 电站的树结构
  const [stationTreeData, setStationTreeData] = useState<any[]>([])
  // 设备树
  const [deviceTreeData, setDeviceTreeData] = useState<any[]>([])
  const [title, setTitle] = useState('')

  useEffect(() => {
    getStationListByUser().then((data) => {
      stationList.current = data
      const stree = handleTree(data)
      setStationTreeData(stree)
    })
    const { type } = props
    if (type == 'add') {
      setTitle('新建')
    } else if (type == 'edit') {
      setTitle('编辑')
    } else {
      setTitle('另存为')
    }
  }, [])

  useEffect(() => {
    if (props.fileId) {
      getFileInfo(props.fileId)
    }
  }, [props.fileId])

  //查询文件元信息
  const getFileInfo = async (fileId: number) => {
    const data = await FileApi.getGraphFileMeta(fileId)
    form.setFieldsValue(data)
    getDeviceTree(data.substationId)
  }
  //查询状态树
  const getDeviceTree = (stationId: number) => {
    stationAndDeviceList(stationId).then((data: any[]) => {
      const list = data.filter(
        (n) =>
          n.productCategoryCode && !['EDGE', 'PCS', 'BMS', 'AM'].includes(n.productCategoryCode)
      )
      const tree = handleTree(list)
      setDeviceTreeData(tree)
    })
  }

  //保存按钮
  const onSave = () => {
    form
      .validateFields()
      .then((values) => {
        const { stationId } = values
        const station: any = stationList.current.find((n: any) => n.stationId == stationId)
        if (station && station.parentId) {
          // 如果选中的子站， 把父站的id 设一下
          values.stationId = station.parentId
          values.substationId = stationId
        } else {
          values.substationId = stationId
        }
        const { type } = props
        if (type == 'edit') {
          values.id = props.fileId
        }
        props.onOk && props.onOk(values)
      })
      .catch((err) => {})
  }

  return (
    <DraggableDialog
      title={title}
      open={true}
      onCancel={props.onClose}
      width={450}
      footer={[
        <Button
          key="cancle"
          size="small"
          className="font-size-12px! mr-20px"
          onClick={(e) => props.onClose && props.onClose()}
        >
          取消
        </Button>,
        <Button
          type="primary"
          key="ok"
          size="small"
          className="font-size-12px!"
          onClick={(e) => onSave()}
        >
          确定
        </Button>
      ]}
    >
      <Form
        name="fileForm"
        layout="horizontal"
        form={form}
        {...layout}
        size="small"
        initialValues={initFormValues}
        autoComplete="off"
      >
        <Form.Item<FieldType>
          label="名称"
          name="name"
          rules={[{ required: true, message: '名称不能为空' }]}
        >
          <Input className="h-26px" />
        </Form.Item>

        <Form.Item<FieldType>
          label="场站"
          name="stationId"
          rules={[{ required: true, message: '归属场站不能为空' }]}
          className="font-size-12px!"
        >
          <TreeSelect
            showSearch
            style={{ width: '100%' }}
            className="w-100% h-26px font-size-12px"
            popupClassName="font-size-12px!"
            dropdownStyle={{ minWidth: 200, fontSize: '12px' }}
            placeholder="请选择电站"
            allowClear
            treeDefaultExpandAll
            fieldNames={{
              label: 'stationName',
              value: 'id'
            }}
            treeData={stationTreeData}
            onChange={(v) => {
              form.setFieldValue('deviceCode', '')
              getDeviceTree(v)
            }}
          />
        </Form.Item>

        <Form.Item<FieldType> label="设备" name="deviceCode" rules={[{ required: false }]}>
          <TreeSelect
            showSearch
            style={{ width: '100%' }}
            className="w-100% h-26px font-size-12px"
            popupClassName="font-size-12px!"
            dropdownStyle={{ minWidth: 200, overflow: 'auto', fontSize: '12px' }}
            placeholder="请选择设备"
            allowClear
            treeDefaultExpandAll
            fieldNames={{
              label: 'deviceName',
              value: 'deviceCode'
            }}
            treeData={deviceTreeData}
          />
        </Form.Item>

        <Form.Item<FieldType> label="类型" name="type" rules={[{ required: true }]}>
          <Select className="h-26px" options={FILE_TYPE_OPTIONS} />
        </Form.Item>

        <Form.Item<FieldType> label="状态" name="status" rules={[{ required: true }]}>
          <Select className="h-26px" options={FILE_STATUS_OPTIONS} />
        </Form.Item>
        <Form.Item<FieldType> label="说明" name="desc" rules={[{ required: false }]}>
          <Input.TextArea />
        </Form.Item>
      </Form>
    </DraggableDialog>
  )
}
